/*
 * @Description: 上传附件
 * @Version: V1.0.0
 * @Author: 黄鑫
 * @Date: 2024-08-21 15:18:29
 * @LastEditors: 黄鑫
 * @LastEditTime: 2025-09-04
 * @FilePath: UploadFileView.dart
 * @Props: 
 * @Remarks: 
 */
import 'dart:io';
import 'package:file_picker/file_picker.dart';
import 'package:flutter/material.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:get/get.dart';
import 'package:hx_base/pages/BaseToast.dart';
import 'package:hx_base/resource/Assets.dart';
import 'package:hx_base/utils/HXUtils.dart';
import 'package:hx_base/utils/PermissionCheckUtils.dart';

class UploadFileView extends StatelessWidget {
  // 选择附件的理由
  String reason;

  /// 组件布局
  MainAxisAlignment? mainAxisAlignment;
  CrossAxisAlignment? crossAxisAlignment;
  EdgeInsets? margin;
  EdgeInsets? padding;

  // 列表装饰
  EdgeInsets? itemMargin;
  EdgeInsets? itemPadding;
  Decoration? itemDecoration;

  /// 返回文件数组
  Function(List<File> fileList) callbackFile;

  UploadFileView({
    super.key,
    this.mainAxisAlignment,
    this.crossAxisAlignment,
    this.margin,
    this.padding,
    this.itemMargin,
    this.itemPadding,
    this.itemDecoration,
    required this.callbackFile,
    required this.reason,
  });

  var fileList = <File>[].obs;

  // 定义支持的文件后缀
  List<String> supportedFileExtensions = [
    '.doc',
    '.docx',
    '.pdf',
    '.xlsx',
    '.xls',
    ".txt"
  ];

  ///添加图片
  addFile() async {
    if (await PermissionCheckUtils.file(reason)) {
      FilePickerResult? result = await FilePicker.platform.pickFiles();
      if (result != null) {
        File file = File(result.files.single.path!);
        // 判断是否为支持的图片类型
        bool isFile = supportedFileExtensions
            .any((extension) => file.path.endsWith(extension));
        if (isFile) {
          fileList.add(file);
          callbackFile(fileList);
        } else {
          BaseToast.showError("请选择正确的文件类型");
        }
      }
    }
  }

  @override
  Widget build(BuildContext context) {
    return Container(
      margin: margin,
      padding: padding,
      child: Column(
        crossAxisAlignment: crossAxisAlignment ?? CrossAxisAlignment.center,
        mainAxisAlignment: mainAxisAlignment ?? MainAxisAlignment.start,
        children: [
          Row(
            children: [
              Text(
                "上传附件",
                style: TextStyle(
                  fontSize: 15.sp,
                  fontWeight: FontWeight.bold,
                ),
              ),
              IconButton(
                onPressed: () => addFile(),
                icon: Icon(Icons.add),
                style: ButtonStyle(
                  minimumSize: WidgetStatePropertyAll(Size(0, 0)),
                  tapTargetSize: MaterialTapTargetSize.shrinkWrap,
                  padding: WidgetStatePropertyAll(EdgeInsets.all(5)),
                ),
              ),
            ],
          ),
          Container(
            margin: EdgeInsets.only(bottom: 5.h),
            child: Text(
              "仅限上传doc、docx、pdf、xlsx、xls、txt格式的文件，大小不大于5M",
              style: TextStyle(
                fontSize: 10.sp,
              ),
            ),
          ),
          setListView()
        ],
      ),
    );
  }

  setListView() {
    return Obx(() => Column(
          children: fileList.map((e) {
            var pathName = e.path.split("/").last;
            final fileType = pathName.split(".").last;
            return Container(
              margin: itemMargin,
              decoration: itemDecoration,
              padding: itemPadding,
              child: Row(
                children: [
                  HXUtils.getImageIcon(fileType),
                  Expanded(
                    child: Container(
                      margin: EdgeInsets.only(right: 5.w, left: 10.w),
                      child: Text(
                        e.path.split("/").last,
                        softWrap: true,
                        overflow: TextOverflow.visible,
                      ),
                    ),
                  ),
                  IconButton(
                    onPressed: () {
                      fileList.remove(e);
                      callbackFile(fileList);
                    },
                    style: ButtonStyle(
                      padding: WidgetStatePropertyAll(
                        EdgeInsets.symmetric(horizontal: 10.w, vertical: 2.h),
                      ),
                      tapTargetSize: MaterialTapTargetSize.shrinkWrap,
                      minimumSize: WidgetStatePropertyAll(Size(0, 0)),
                    ),
                    icon: Image.asset(
                      Assets.imagesCloseRoundIcon,
                      width: 18.w,
                      height: 18.w,
                      package: "hx_base",
                    ),
                  ),
                ],
              ),
            );
          }).toList(),
        ));
  }
}
